package com.ddstation.hzsc_invs.institution_details.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ddstation.chart.util.CvnDateUtil;
import com.ddstation.crm.institution.entity.DtHealthManageInstitutionEntity;
import com.ddstation.crm.institution.entity.DtHealthManageInstitutionInvsExpandEntity;
import com.ddstation.crm.institution.mapper.DtHealthManageInstitutionMapper;
import com.ddstation.home_page.model.HpCommonParModel;
import com.ddstation.home_page.model.NameValueModel;
import com.ddstation.hzsc_invs.institution_details.model.InstitutionDetailsDoctorModel;
import com.ddstation.master.entity.MaDataDictionaryEntity;
import com.ddstation.master.mapper.MaDataDictionaryMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class InstitutionDetailsController {

    /*@RequestMapping(value="invs_institution_details.do/load_institution_details", method= RequestMethod.POST)
    public @ResponseBody Map<String, Object> loadInstitutionDetails(
            @RequestParam String institutionId,
            HttpSession session) {
        Map<String, Object> ret = new HashMap<String, Object>();
        try {
            if (StringUtils.isEmpty(institutionId)) {
                throw new Exception("请求异常！");
            }

            HpCommonParModel _p = new HpCommonParModel();
            String[] dateRange = CvnDateUtil.cvnDateRange(1);
            _p.setDtFrom(dateRange[0]);
            _p.setDtTo(dateRange[1]);
            _p.setInstitutionId(institutionId);

            JSONObject info = new JSONObject();

            //机构基本信息
            DtHealthManageInstitutionEntity dtHealthManageInstitutionEntity = dtHealthManageInstitutionMapper.selectInstitutionInfoByInstitutionId(institutionId);
            String technicalOffices = getTechnicalOfficesNames(dtHealthManageInstitutionEntity.getTechnicalOffices());
            dtHealthManageInstitutionEntity.setTechnicalOffices(technicalOffices);
            info.put("baseInfo", dtHealthManageInstitutionEntity);

            //医师、 护士
            HashMap rolesCount = dtHealthManageInstitutionMapper.getInstitutionRoleCount(_p);
            info.put("roles", rolesCount);

            //质控评分
            info.put("qualityScore", "未评分");

            //行业协会评价
            info.put("industryScore", "未评价");

            //信用评价登记
            info.put("creditLevel", "未登记");

            //公众满意度
            List<HashMap> satisfactionList = dtHealthManageInstitutionMapper.getSatisfactionCounts(institutionId, 0, null, null);
            info.put("satisfaction", satisfactionList);

            //诊疗行为 => 病历数、处方数、处方违规数
            JSONObject prescriptionSupervision = new JSONObject();
            int hisCnt = dtHealthManageInstitutionMapper.statisticsDailyCaseInstitution(_p);
            prescriptionSupervision.put("hisCount", hisCnt);

            int prescriptionsCnt = dtHealthManageInstitutionMapper.statisticsDailyPresInstitution(institutionId, null, null);
            prescriptionSupervision.put("prescriptionsCount", prescriptionsCnt);

            //近一周 违规处方
            Integer[] pTypes = {40};
            _p.setBusinessTypeList(pTypes);
            int violationsCnt = dtHealthManageInstitutionMapper.selectPrescriptionViolationInstitution(_p);
            prescriptionSupervision.put("violationsCount", violationsCnt);
            info.put("prescriptionSupervision", prescriptionSupervision);

            //近一月 违规台账
            Integer[] aTypes = {10,20,30};
            _p.setBusinessTypeList(aTypes);
            dateRange = CvnDateUtil.cvnDateRange(3);
            _p.setDtFrom(dateRange[0]);
            _p.setDtTo(dateRange[1]);
            HashMap accountType = dtHealthManageInstitutionMapper.selectAccountTypeInstitution(_p);
            info.put("accountSupervision", accountType);

            //自律自查
            JSONObject autonomyExamination = new JSONObject();
            autonomyExamination.put("examinationCount", 0);
            autonomyExamination.put("rectificationCount", 0);
            autonomyExamination.put("reportCount", 0);
            info.put("autonomyExamination", autonomyExamination);

            //行政处罚
            info.put("administrativeSanctionCount", 0);

            ret.put("info", info);
            ret.put("errorcode",0);

        } catch (java.lang.Exception e) {
            ret.put("errorcode", -1);
            ret.put("errormsg", e.getMessage());
        }

        return ret;
    }*/

    @RequestMapping(value="invs_institution_details.do/load_institution_details", method= RequestMethod.POST)
    public @ResponseBody Map<String, Object> loadInstitutionDetails(
            @RequestParam String institutionId,
            HttpSession session) {
        Map<String, Object> ret = new HashMap<String, Object>();
        try {
            if (StringUtils.isEmpty(institutionId)) {
                throw new Exception("请求异常！");
            }

            HpCommonParModel _p = new HpCommonParModel();
            String[] dateRange = CvnDateUtil.cvnDateRange(1);
            _p.setDtFrom(dateRange[0]);
            _p.setDtTo(dateRange[1]);
            _p.setInstitutionId(institutionId);

            JSONObject info = new JSONObject();
            List<MaDataDictionaryEntity> technicalOfficesList = maDataDictionaryMapper.selectByCategoryId("technical_offices");
            List<MaDataDictionaryEntity> scopePracticeList = maDataDictionaryMapper.selectByCategoryId("scope_practice");

            //机构基本信息
            JSONObject baseInfo = new JSONObject();
            DtHealthManageInstitutionEntity institutionEntity = dtHealthManageInstitutionMapper.selectInstitutionInfoByInstitutionId(institutionId);
            String technicalOffices = getDictionaryNames(institutionEntity.getTechnicalOffices(), technicalOfficesList);
            institutionEntity.setTechnicalOffices(technicalOffices);
            baseInfo.put("technicalOffices", institutionEntity.getTechnicalOffices());
            baseInfo.put("occupationalLicenceEndDate", institutionEntity.getOccupationalLicenceEndDate());
            info.put("baseInfo", baseInfo);

            //质控评分、行业协会评价、信用评价等级、公众满意度评价
            JSONObject scoreInfo = new JSONObject();

            scoreInfo.put("quality", "0");
            scoreInfo.put("industry", "0");
            scoreInfo.put("credit", "良好");
            scoreInfo.put("satisfaction", "满意");
            info.put("scoreInfo", scoreInfo);

            //医生、护士信息
            List<InstitutionDetailsDoctorModel> doctorList = dtHealthManageInstitutionMapper.getDoctorsInfo(_p);
            for (InstitutionDetailsDoctorModel one:doctorList) {
                one.setScopePractice(getDictionaryNames(one.getScopePractice(), scopePracticeList));
            }
            info.put("doctorList", doctorList);

            //诊疗行为 => 病历数、处方数、处方违规数
            JSONObject prescriptionSupervision = new JSONObject();
            int hisCnt = dtHealthManageInstitutionMapper.statisticsDailyCaseInstitution(_p);
            prescriptionSupervision.put("hisCount", hisCnt);

            int prescriptionsCnt = dtHealthManageInstitutionMapper.statisticsInstitutionDailyPrescription(_p);
            prescriptionSupervision.put("prescriptionsCount", prescriptionsCnt);

            //近一周 违规处方
            Integer[] pTypes = {40};
            _p.setBusinessTypeList(pTypes);
            //处方未监管 忽略异常
            int violationsCnt = institutionEntity.getPrescriptionInvs() == null ? 0 : dtHealthManageInstitutionMapper.selectPrescriptionViolationInstitution(_p);
            prescriptionSupervision.put("violationsCount", violationsCnt);
            info.put("prescriptionSupervision", prescriptionSupervision);

            //近一月 违规台账
            Integer[] aTypes = {10,20,30};
            _p.setBusinessTypeList(aTypes);
            dateRange = CvnDateUtil.cvnDateRange(3);
            _p.setDtFrom(dateRange[0]);
            _p.setDtTo(dateRange[1]);
            HashMap accountType = dtHealthManageInstitutionMapper.selectAccountTypeInstitution(_p);
            info.put("accountSupervision", accountType);

            //自律自查
            JSONObject autonomyExamination = new JSONObject();
            autonomyExamination.put("examinationCount", 0);
            autonomyExamination.put("rectificationCount", 0);
            autonomyExamination.put("reportCount", 0);
            info.put("autonomyExamination", autonomyExamination);

            //行政处罚
            info.put("punishCount", 0);

            ret.put("info", info);
            ret.put("errorcode",0);

        } catch (java.lang.Exception e) {
            ret.put("errorcode", -1);
            ret.put("errormsg", e.getMessage());
        }

        return ret;
    }

    /**
     * 机构诊疗行为数据
     * @param institutionId
     * @param dtFrom
     * @param dtTo
     * @param session
     * @return
     */
    @RequestMapping(value="invs_institution_details.do/load_prescription_details", method= RequestMethod.POST)
    public @ResponseBody Map<String, Object> loadPrescriptionDetails(
            @RequestParam String institutionId,
            @RequestParam String dtFrom,
            @RequestParam String dtTo,
            HttpSession session) {
        Map<String, Object> ret = new HashMap<String, Object>();
        try {
            if (StringUtils.isEmpty(institutionId)) {
                throw new Exception("请求异常！");
            }

            HpCommonParModel _p = new HpCommonParModel();
            _p.setDtFrom(dtFrom);
            _p.setDtTo(dtTo);
            _p.setInstitutionId(institutionId);

            JSONObject info = new JSONObject();

            //诊疗行为 => 病历数、处方数、处方违规数
            JSONObject prescriptionSupervision = new JSONObject();
            int hisCnt = dtHealthManageInstitutionMapper.statisticsDailyCaseInstitution(_p);
            prescriptionSupervision.put("hisCount", hisCnt);

            int prescriptionsCnt = dtHealthManageInstitutionMapper.statisticsInstitutionDailyPrescription(_p);
            prescriptionSupervision.put("prescriptionsCount", prescriptionsCnt);

            //近一周 违规处方
            Integer[] pTypes = {40};
            _p.setBusinessTypeList(pTypes);
            DtHealthManageInstitutionEntity institutionEntity = dtHealthManageInstitutionMapper.selectInstitutionInfoByInstitutionId(institutionId);
            int violationsCnt = institutionEntity.getPrescriptionInvs() == null ? 0 : dtHealthManageInstitutionMapper.selectPrescriptionViolationInstitution(_p);
            prescriptionSupervision.put("violationsCount", violationsCnt);
            info.put("prescriptionSupervision", prescriptionSupervision);

            ret.put("info", info);
            ret.put("errorcode",0);

        } catch (java.lang.Exception e) {
            ret.put("errorcode", -1);
            ret.put("errormsg", e.getMessage());
        }

        return ret;
    }

    /**
     * 机构消毒灭菌
     * @param institutionId
     * @param dtFrom
     * @param dtTo
     * @param session
     * @return
     */
    @RequestMapping(value="invs_institution_details.do/load_account_details", method= RequestMethod.POST)
    public @ResponseBody Map<String, Object> loadAccountDetails(
            @RequestParam String institutionId,
            @RequestParam String dtFrom,
            @RequestParam String dtTo,
            HttpSession session) {
        Map<String, Object> ret = new HashMap<String, Object>();
        try {
            if (StringUtils.isEmpty(institutionId)) {
                throw new Exception("请求异常！");
            }

            HpCommonParModel _p = new HpCommonParModel();
            _p.setDtFrom(dtFrom);
            _p.setDtTo(dtTo);
            _p.setInstitutionId(institutionId);

            Integer[] aTypes = {10,20,30};
            _p.setBusinessTypeList(aTypes);

            JSONObject info = new JSONObject();
            HashMap accountType = dtHealthManageInstitutionMapper.selectAccountTypeInstitution(_p);
            info.put("accountSupervision", accountType);

            ret.put("info", info);
            ret.put("errorcode",0);

        } catch (java.lang.Exception e) {
            ret.put("errorcode", -1);
            ret.put("errormsg", e.getMessage());
        }

        return ret;
    }

    /**
     * 机构自律自查
     * @param institutionId
     * @param dtFrom
     * @param session
     * @return
     */
    @RequestMapping(value="invs_institution_details.do/load_examination_details", method= RequestMethod.POST)
    public @ResponseBody Map<String, Object> loadExaminationDetails(
            @RequestParam String institutionId,
            @RequestParam String dtFrom,
            HttpSession session) {
        Map<String, Object> ret = new HashMap<String, Object>();
        try {
            if (StringUtils.isEmpty(institutionId)) {
                throw new Exception("请求异常！");
            }

            HpCommonParModel _p = new HpCommonParModel();
            _p.setDtFrom(dtFrom);
            _p.setInstitutionId(institutionId);

            JSONObject info = new JSONObject();

            //自律自查
            JSONObject autonomyExamination = new JSONObject();
            autonomyExamination.put("examinationCount", 0);
            autonomyExamination.put("rectificationCount", 0);
            autonomyExamination.put("reportCount", 0);
            info.put("autonomyExamination", autonomyExamination);

            ret.put("info", info);
            ret.put("errorcode",0);

        } catch (java.lang.Exception e) {
            ret.put("errorcode", -1);
            ret.put("errormsg", e.getMessage());
        }

        return ret;
    }

    /**
     * 机构行政处罚
     * @param institutionId
     * @param dtFrom
     * @param dtTo
     * @param session
     * @return
     */
    @RequestMapping(value="invs_institution_details.do/load_punish_details", method= RequestMethod.POST)
    public @ResponseBody Map<String, Object> loadPunishDetails(
            @RequestParam String institutionId,
            @RequestParam String dtFrom,
            @RequestParam String dtTo,
            HttpSession session) {
        Map<String, Object> ret = new HashMap<String, Object>();
        try {
            if (StringUtils.isEmpty(institutionId)) {
                throw new Exception("请求异常！");
            }

            HpCommonParModel _p = new HpCommonParModel();
            _p.setDtFrom(dtFrom);
            _p.setDtTo(dtTo);
            _p.setInstitutionId(institutionId);

            JSONObject info = new JSONObject();

            //行政处罚
            info.put("punishCount", 0);

            ret.put("info", info);
            ret.put("errorcode",0);

        } catch (java.lang.Exception e) {
            ret.put("errorcode", -1);
            ret.put("errormsg", e.getMessage());
        }

        return ret;
    }

    /**
     *  id 转 name
     * @param ids 01,02,03
     * @return
     */
    public String getDictionaryNames(String ids, List<MaDataDictionaryEntity> dictsList) {

        if (!StringUtils.isEmpty(ids)) {
            String[] idsArr = ids.split(",");
            ids = "";
            for (int i=0; i < idsArr.length; i++) {
                for (MaDataDictionaryEntity dict:dictsList) {
                    if (idsArr[i].equals(dict.getValue())) {
                        if (i == idsArr.length - 1) {
                            ids += dict.getFullName();
                        } else {
                            ids += dict.getFullName() + ",";
                        }
                        break;
                    }
                }
            }
        }
        return ids;
    }

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Inject private MaDataDictionaryMapper maDataDictionaryMapper;
    @Inject private DtHealthManageInstitutionMapper dtHealthManageInstitutionMapper;
}
